﻿#include "beanstalk.h"
#include "bspool.h"

#include <stdio.h>
#include <assert.h>
#include <inttypes.h>

#ifdef _WIN32
#include <WinSock2.h>
#endif

#define USE_POOL 1

int main() {
    BSJ job;
    char *yaml;
    int64_t id;
    int a,b,c,i;
	bspool_t pool;
	uint32_t time;

#ifdef _WIN32
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif

	//使用polling
	bs_select_polling();

	bsp_init(&pool);
	bs_init_job(&job);

    bs_version(&a, &b, &c);
    printf("beanstalk-client version %d.%d.%d\n", a,b,c);

	time = GetTickCount();

	for (i = 0; i < 1; ++i) {
#if USE_POOL
		int socket = bsp_connect(&pool, "192.168.1.15", 11300);
#else
		int socket = bs_connect("192.168.1.15", 11300);
#endif
		assert(socket != BS_STATUS_FAIL);
		assert(bs_ping(socket) == BS_STATUS_OK);
		
		//assert(bs_call(socket, 0, 10, 60, "hello world", 11, &job) == BS_STATUS_OK);
		//printf("call job id: %"PRId64"\n", job.id);

		assert(bs_use(socket, "test") == BS_STATUS_OK);
		assert(bs_watch(socket, "test") == BS_STATUS_OK);
		assert(bs_ignore(socket, "default") == BS_STATUS_OK);


		id = bs_put(socket, 0, 0, 60, "hello world", 11);
		assert(id > 0);
		printf("put job id: %"PRId64"\n", id);

		assert(bs_reserve_with_timeout(socket, 2, &job) == BS_STATUS_OK);

		printf("reserve job id: %"PRId64" size: %lu\n", job.id, job.size);
		printf("%.*s\n", job.size, job.data);


		printf("release job id: %"PRId64"\n", job.id);
		assert(bs_release(socket, job.id, 0, 0) == BS_STATUS_OK);

		assert(bs_peek_ready(socket, &job) == BS_STATUS_OK);
		printf("peek job id: %"PRId64"\n", job.id);
		printf("%.*s\n", job.size, job.data);

		printf("delete job id: %"PRId64"\n", job.id);
		assert(bs_delete(socket, job.id) == BS_STATUS_OK);

		assert(bs_list_tubes(socket, &yaml) == BS_STATUS_OK);
		printf("tubes:\n%s\n", yaml);
		free(yaml);
		assert(bs_list_tubes_watched(socket, &yaml) == BS_STATUS_OK);
		printf("tubes-watched:\n%s\n", yaml);
		free(yaml);
		assert(bs_list_tube_used(socket, &yaml) == BS_STATUS_OK);
		printf("tube-used: %s\n", yaml);
		free(yaml);

		//if (bs_stats(socket, &yaml) == BS_STATUS_OK) {
		//	printf("stats:\n%s\n", yaml);
		//	free(yaml);
		//}
		//else {
		//	printf("stats:error\n");
		//}
#if USE_POOL
		bsp_close(&pool, socket);
#else
		bs_close(socket);
#endif
	}

	bs_deinit_job(&job);
	bsp_deinit(&pool);

	printf("cost time %d\n",GetTickCount()-time);
	getchar();
	return 0;
}
